package com.hejx.managecenter.common.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import javax.persistence.EntityManager;
import java.io.Serializable;

/**
 * @program: managecenter_example
 * @description:
 * @author: hejx
 * @email: doubihah@foxmail.com
 * @create: 2018-06-26 22:20
 **/
public class BaseDaoFactoryBean<T extends JpaRepository<S,ID>,S,ID extends Serializable>
        extends JpaRepositoryFactoryBean<T,S,ID> {

    public BaseDaoFactoryBean(Class<? extends T> repositoryInterface) {
        super(repositoryInterface);
    }

    protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager){
        return new BaseDaoFactory(entityManager);
    }

    private static class BaseDaoFactory extends JpaRepositoryFactory {

        public BaseDaoFactory(EntityManager entityManager) {
            super(entityManager);
        }

        @Override
        @SuppressWarnings({"unchecked"})
        protected <T,ID extends Serializable> SimpleJpaRepository<?,?> getTargetRepository(
                RepositoryInformation information, EntityManager entityManager){
            return new BaseDaoImpl<>((Class<T>)information.getDomainType(),entityManager);
        }

        @Override
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata){
            return BaseDaoImpl.class;
        }


    }
}
